﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;

namespace SensorRWTool
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;

            radioButton2.Checked = true;
            radioButton1.Checked = false;
            comboBox4.Enabled = false;

            previndex = 0;
            baudrateList = new string[] {"2400", "4800", "9600"};
            for (int j = 0; j < baudrateList.Length; j++)
            {
                string baudrate = baudrateList[j];
                comboBox2.Items.Add(baudrate);
                comboBox4.Items.Add(baudrate);
            }
            comboBox2.SelectedIndex = 2;   //默认9600bps
            comboBox4.SelectedIndex = 2;  //默认9600bps

            portList = System.IO.Ports.SerialPort.GetPortNames();
            for (int i = 0; i < portList.Length; i++)
            {
                string name = portList[i];
                comboBox1.Items.Add(name);
                comboBox1.SelectedIndex = 0;//默认显示第一项
            }

            sp = new SerialPort();
            sm = new SensorManager();
            EarthHumiture sEHumiture = new EarthHumiture("土壤温湿度传感器", 0);
            Sensor sWindSpeed = new WindSpeed("风速传感器", 1);
            Sensor sLight = new Light("光照度变送器", 2);
            sm.AddSensor(sEHumiture);
            sm.AddSensor(sWindSpeed);
            sm.AddSensor(sLight);
            sensordescList = new List<string>();
            
            for ( int k = 0; k < sm.GetSensorCount(); k++)
            {
                sensordescList.Add(sm.GetSensor(k).GetSensorDesc());

            }
            for ( int m = 0; m < sensordescList.Count; m++)
            {
                comboBox3.Items.Add(sensordescList[m]);
            }
            comboBox3.SelectedIndex = 0;
        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }
        private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            button2.Enabled = false;
            button3.Enabled = false;

            int addr = -1;

            if ( comboBox1.Text == "")
            {
                MessageBox.Show("请选择串口号!");
                button1.Enabled = true;
                button2.Enabled = true;
                button3.Enabled = true;
                return;
            }
            if (comboBox2.Text == "")
            {
                MessageBox.Show("请选择波特率!");
                button1.Enabled = true;
                button2.Enabled = true;
                button3.Enabled = true;
                return;
            }

            if (comboBox3.Text == "")
            {
                MessageBox.Show("请选择设备!");
                button1.Enabled = true;
                button2.Enabled = true;
                button3.Enabled = true;
                return;
            }
            if ( textBox1.Text != "")
            {
                addr = int.Parse(textBox1.Text);
                if (addr < 0 || addr > 249)
                {
                    MessageBox.Show("非法地址！ 地址范围在0-249之间");
                    button1.Enabled = true;
                    button2.Enabled = true;
                    button3.Enabled = true;
                    return;
                }
            }
            sensor = sm.GetSensor(comboBox3.SelectedIndex);
            try
            {
                sp.PortName = portList[comboBox1.SelectedIndex];                //串口号
                sp.BaudRate = int.Parse(baudrateList[comboBox2.SelectedIndex]); //波特率
                sp.Parity = Parity.None;          //校验位
                sp.StopBits = StopBits.One;       //停止位
                sp.ReadTimeout = 1500;
                sp.Encoding = Encoding.UTF8;
                sp.ReceivedBytesThreshold = 1;
                sp.Open();
            }
            catch
            {
                MessageBox.Show("打开串口失败！");
                button1.Enabled = true;
                button2.Enabled = true;
                button3.Enabled = true;
                return;

            }
            byte[] tmp = sensor.GetQueryFrame(addr);
            for (int i = 0; i < tmp.Length; i++)
            {
                Console.WriteLine(tmp[i]);
            }
            sp.Write(tmp, 0, tmp.Length);

            Thread SerialThread;
            SerialThread = new Thread(DealSerial);
            SerialThread.Start();
        }
        private void DealSerial()
        {
            int arrlen = sensor.responelen;
            byte[] recv = new byte[arrlen];
            //读写指定串口
            int i = 0;
            while (i < 100000000) i++;
            try
            {
                int readbytes = sp.Read(recv, 0, arrlen);
                if (readbytes != arrlen)
                {
                    sp.Close();
                    MessageBox.Show("采集数据失败！");
                    button1.Enabled = true;
                    button2.Enabled = true;
                    button3.Enabled = true;
                    return;
                }
            }
            catch
            {
                MessageBox.Show("采集数据失败！");
                sp.Close();
                button1.Enabled = true;
                button2.Enabled = true;
                button3.Enabled = true;
                return;

            }
            
            if (sensor.ParseData(recv))
            {
                sensor.Display();
            }else
            {
                sp.Close();
                MessageBox.Show("采集数据失败！");
                button1.Enabled = true;
                button2.Enabled = true;
                button3.Enabled = true;
                return;
            }
            sp.Close(); 
            sensor.Display();
            button1.Enabled = true;
            button2.Enabled = true;
            button3.Enabled = true;
        }

        private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
        {
            panel1.Controls.Clear();
            textBox1.Text = "";
            sm.GetSensor(previndex).ClearData();
            sensor = sm.GetSensor(comboBox3.SelectedIndex);
            panel1.Controls.Add(sensor.form);
            sensor.form.Show();
            previndex = comboBox3.SelectedIndex;
        }

        private void groupBox2_Enter(object sender, EventArgs e)
        {

        }

        private void label6_Click(object sender, EventArgs e)
        {

        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            comboBox4.Enabled = true;
            textBox3.Text = "";
            textBox3.Enabled = false;
            button2.Text = "设置设备波特率";

        }

        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            textBox3.Enabled = true;
            comboBox4.Enabled = false;
            button2.Text = "设置设备地址";
        }

        private void comboBox4_SelectedIndexChanged(object sender, EventArgs e)
        {
        }

        private void groupBox3_Enter(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            button2.Enabled = false;
            button3.Enabled = false;

            int addr = -1;

            if (comboBox1.Text == "")
            {
                MessageBox.Show("请选择串口号!");
                button1.Enabled = true;
                button2.Enabled = true;
                button3.Enabled = true;
                return;
            }
            if (comboBox2.Text == "")
            {
                MessageBox.Show("请选择波特率!");
                button1.Enabled = true;
                button2.Enabled = true;
                button3.Enabled = true;
                return;
            }
            if (comboBox3.Text == "")
            {
                MessageBox.Show("请选择设备!");
                button1.Enabled = true;
                button2.Enabled = true;
                button3.Enabled = true;
                return;
            }

            if (textBox1.Text != "")
            {
                addr = int.Parse(textBox1.Text);
                if (addr < 0 || addr > 249)
                {
                    MessageBox.Show("非法地址！ 地址范围在0-249之间");
                    button1.Enabled = true;
                    button2.Enabled = true;
                    button3.Enabled = true;
                    return;
                }
            }

            sensor = sm.GetSensor(comboBox3.SelectedIndex);
            try
            {
                sp.PortName = portList[comboBox1.SelectedIndex];                //串口号
                sp.BaudRate = int.Parse(baudrateList[comboBox2.SelectedIndex]); //波特率
                sp.Parity = Parity.None;          //校验位
                sp.StopBits = StopBits.One;       //停止位
                sp.ReadTimeout = 1500;
                sp.Encoding = Encoding.UTF8;
                sp.ReceivedBytesThreshold = 1;
                sp.Open();
            }
            catch
            {
                MessageBox.Show("打开串口失败！");
                button1.Enabled = true;
                button2.Enabled = true;
                button3.Enabled = true;
                return;
            }
            if (radioButton1.Checked == true)
            {
                if (comboBox4.Text == "")
                {
                    MessageBox.Show("请选择要设置的波特率！！");
                    button1.Enabled = true;
                    button2.Enabled = true;
                    button3.Enabled = true;
                    sp.Close();
                    return;
                }
                int baudrate;
                baudrate = int.Parse(baudrateList[comboBox4.SelectedIndex]);
                byte[] frame = sensor.GetConfigBaudRateFrame(addr, baudrate);
                sp.Write(frame, 0, frame.Length);
                Thread SerialThread;
                SerialThread = new Thread(ConfigBaudRateThread);
                SerialThread.Start();

            }
            else if (radioButton2.Checked == true)
            {
                if (textBox3.Text == "")
                {
                    MessageBox.Show("请填写需要设置的地址！！");
                    button1.Enabled = true;
                    button2.Enabled = true;
                    button3.Enabled = true;
                    sp.Close();
                    return;
                }
                int destaddr;
                destaddr = int.Parse(textBox3.Text);
                if (destaddr < 0 || destaddr > 249)
                {
                    MessageBox.Show("非法地址！ 地址范围在0-249之间");
                    button1.Enabled = true;
                    button2.Enabled = true;
                    button3.Enabled = true;
                    sp.Close();
                    return;
                }
                byte[] frame = sensor.GetConfigAddrFrame(destaddr, addr);
                sp.Write(frame, 0, frame.Length);
                Thread SerialThread;
                SerialThread = new Thread(ConfigAddrThread);
                SerialThread.Start();
            }
        }

        private void ConfigBaudRateThread()
        {
            byte[] recv = new byte[8];
            int i = 0;
            while (i < 100000000 ) i++;
            try
            {
                int readbytes = sp.Read(recv, 0, 8);
                if (readbytes != 8)
                {
                    sp.Close();
                    MessageBox.Show("波特率设置失败！");
                    button1.Enabled = true;
                    button2.Enabled = true;
                    button3.Enabled = true;
                    return;
                }
            }
            catch
            {
                sp.Close();
                MessageBox.Show("波特率设置失败！");
                button1.Enabled = true;
                button2.Enabled = true;
                button3.Enabled = true;
                return;

            }
            sp.Close();

            if (sensor.ParseConfigBaudRateFrame(recv) == 0)
            {
                MessageBox.Show("波特率设置成功!");
               
            }else
            {
                MessageBox.Show("波特率设置失败！");

            }
            button1.Enabled = true;
            button2.Enabled = true;
            button3.Enabled = true;
            return;

        }

        private void ConfigAddrThread()
        {
            byte[] recv = new byte[8];
            int i = 0;
            while (i < 100000000) i++;
            try
            {
                int readbytes = sp.Read(recv, 0, 8);
                if (readbytes != 8)
                {
                    sp.Close();
                    MessageBox.Show("地址设置失败！");
                    button1.Enabled = true;
                    button2.Enabled = true;
                    button3.Enabled = true;
                    return;
                }
            }
            catch
            {
                sp.Close();
                MessageBox.Show("地址设置失败！");
                button1.Enabled = true;
                button2.Enabled = true;
                button3.Enabled = true;
                return;

            }
            sp.Close();

            if (sensor.ParseConfigAddrFrame(recv) == 0)
            {
                MessageBox.Show("地址设置成功!");
            }
            else
            {
                MessageBox.Show("地址设置失败！");
            }
            button1.Enabled = true;
            button2.Enabled = true;
            button3.Enabled = true;
            textBox3.Text = "";
            return;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            //自动探测传感器参数
            button1.Enabled = false;
            button2.Enabled = false;
            button3.Enabled = false;

            if (comboBox1.Text == "")
            {
                MessageBox.Show("请选择串口号!");
                button1.Enabled = true;
                button2.Enabled = true;
                button3.Enabled = true;
                return;
            }
            Thread SerialThread;
            SerialThread = new Thread(AutoScan);
            SerialThread.Start();
        }

        public void AutoScan()
        {
            sensor = sm.GetSensor(comboBox3.SelectedIndex);

            for (int i = 0; i < 3; i++)
            {
                try
                {
                    sp.PortName = portList[comboBox1.SelectedIndex];                //串口号
                    sp.BaudRate = int.Parse(baudrateList[i]); //波特率
                    sp.Parity = Parity.None;          //校验位
                    sp.StopBits = StopBits.One;       //停止位
                    sp.ReadTimeout = 1500;
                    sp.Encoding = Encoding.UTF8;
                    sp.ReceivedBytesThreshold = 1;
                    sp.Open();
                }
                catch
                {
                    continue;

                }
                byte[] frame = sensor.GetAutoScanFrame();
                sp.Write(frame, 0, frame.Length);
                int k = 0;
                while (k < 100000000) k++;
                byte[] recv = new byte[9];
                try
                {
                    int readbytes = sp.Read(recv, 0, 9);
                    if (readbytes != 9)
                    {
                        sp.Close();
                        continue;

                    }
                }
                catch
                {
                    sp.Close();
                    continue;

                }
                sp.Close();
                int[] ret;
                if ((ret = sensor.ParseAutoScanFrame(recv) )!= null)
                {
                    if ((ret[0] == 2400 || ret[0] == 4800 ||
                        ret[0] == 9600) && (ret[1] >= 0 && ret[1] <= 249))
                    {
                        MessageBox.Show("探测成功!");
                        switch(ret[0])
                        {
                            case 2400:
                                comboBox2.SelectedIndex = 0;
                                break;
                            case 4800:
                                comboBox2.SelectedIndex = 1;
                                break;
                            case 9600:
                                comboBox2.SelectedIndex = 2;
                                break;
                        }
                        textBox1.Text = ret[1].ToString();
                        button1.Enabled = true;
                        button2.Enabled = true;
                        button3.Enabled = true;
                        return;
                    }
                    
                }
            }
            MessageBox.Show("探测失败!");
            button1.Enabled = true;
            button2.Enabled = true;
            button3.Enabled = true;
            return;
        }
    }
}
